package api

import (
	"net/http"
	"strconv"

	"erp/config"
	"erp/logic"
	"erp/model"
	"erp/util"

	"github.com/gin-gonic/gin"
)

func RegisterShipmentRoutes(r *gin.Engine) {
	s := logic.ShipmentService{DB: config.DB}

	// 创建发货单
	r.POST("/shipments", func(c *gin.Context) {
		var shipment model.Shipment
		if err := c.ShouldBindJSON(&shipment); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}

		if err := s.CreateShipment(&shipment); err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		c.JSON(http.StatusOK, shipment)
	})

	// 分页与搜索（按订单ID或状态）
	r.GET("/shipments", func(c *gin.Context) {
		p := util.GetPage(c)
		var list []model.Shipment
		q := config.DB.Model(&model.Shipment{}).Preload("Order")
		if orderID := c.Query("order_id"); orderID != "" {
			q = q.Where("order_id = ?", orderID)
		}
		if status := c.Query("status"); status != "" {
			q = q.Where("status = ?", status)
		}
		var total int64
		q.Count(&total)
		if err := q.Offset(p.Offset).Limit(p.Limit).Order("id DESC").Find(&list).Error; err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		c.JSON(http.StatusOK, gin.H{"items": list, "total": total, "page": p.Page, "pageSize": p.PageSize})
	})

	// 获取发货单详情
	r.GET("/shipments/:id", func(c *gin.Context) {
		id64, _ := strconv.ParseUint(c.Param("id"), 10, 64)
		shipment, err := s.GetShipment(uint(id64))
		if err != nil {
			c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
			return
		}
		c.JSON(http.StatusOK, shipment)
	})

	// 更新发货状态
	r.PUT("/shipments/:id/status", func(c *gin.Context) {
		id64, _ := strconv.ParseUint(c.Param("id"), 10, 64)
		var req struct {
			Status string `json:"status"`
			Notes  string `json:"notes"`
		}
		if err := c.ShouldBindJSON(&req); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}
		if req.Status == "" {
			c.JSON(http.StatusBadRequest, gin.H{"error": "status 不能为空"})
			return
		}

		if err := s.UpdateShipmentStatus(uint(id64), req.Status, req.Notes); err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		c.JSON(http.StatusOK, gin.H{"message": "发货状态更新成功"})
	})

	// 删除发货单
	r.DELETE("/shipments/:id", func(c *gin.Context) {
		id64, _ := strconv.ParseUint(c.Param("id"), 10, 64)
		if err := s.DeleteShipment(uint(id64)); err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		c.Status(http.StatusNoContent)
	})

	// 送货单打印数据
	r.GET("/delivery_note/:order_id", func(c *gin.Context) {
		var order model.Order
		id := c.Param("order_id")
		if err := config.DB.Preload("Items.Product").First(&order, id).Error; err != nil {
			c.JSON(http.StatusNotFound, gin.H{"error": "订单不存在"})
			return
		}
		var shipment model.Shipment
		_ = config.DB.Where("order_id = ?", id).First(&shipment).Error
		c.JSON(http.StatusOK, gin.H{"order": order, "shipment": shipment})
	})

	// 批量发货
	r.POST("/shipments/batch", func(c *gin.Context) {
		var req struct {
			OrderIDs []uint `json:"order_ids"`
		}
		if err := c.ShouldBindJSON(&req); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}

		shipments, err := s.BatchCreateShipments(req.OrderIDs)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		c.JSON(http.StatusOK, gin.H{"message": "批量发货成功", "shipments": shipments})
	})

	// 获取发货统计
	r.GET("/shipments/stats", func(c *gin.Context) {
		stats, err := s.GetShipmentStats()
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		c.JSON(http.StatusOK, stats)
	})
}
